#!/bin/sh
#exec scala -J-Xms128m -J-Xmx128m "`cygpath -w $0`" "$@"
exec scala -J-Xms128m -J-Xmx128m "$0" "$@"
!#
import scala.collection.mutable._
var cpuList  = ArrayBuffer("x86","ppc","ia64","arm","pa64","sparc","zero")
val osList   = ArrayBuffer("linux","bsd","windows","win32","vms","solaris","hp-ux")
val miscList = ArrayBuffer("shark", "c1", "adlc", ".svn", ".hg")

import java.nio.file._
import scala.collection.JavaConversions._
implicit def StringToPath( name:String ) = FileSystems.getDefault().getPath(name)

var result=new java.util.ArrayList[String](200)

def Usage:Unit = {
    println( "build_cscope under hotspot/src directory" )
}

def trace( mesg:String ): Unit = {
    println( "["+new java.util.Date()+"] "+mesg )
}

// sanity check, must be under src directory
import scala.sys.props

trace( "sanity checking" )
val pwd = props( "user.dir" )
if( !Files.isDirectory( pwd+"/share" ) || !Files.isDirectory( pwd+"/os" )  || !Files.isDirectory( pwd+"/cpu" ) || !Files.isDirectory( pwd+"/os_cpu" ) )
{
    Usage
    System.exit(-1)
}

trace( "pre work" )
// prepare keyword list by environment
val parent = pwd.getParent
if( Files.isDirectory( parent+"/.hg" ) ){
    /* openjdk, we care linux/x86 */
    cpuList -= "x86"
    osList  -= "linux"
}else{
    cpuList -= "ia64"
    osList  -= "hp-ux"
}

object visitor extends SimpleFileVisitor[Path]{
    override def visitFile( file:Path, attrs: java.nio.file.attribute.BasicFileAttributes ):FileVisitResult = {

        var accept = true
        val name = file.toString
        /* checking file type, accept *.cpp or *.hpp */
        accept = name.endsWith( ".cpp" ) || name.endsWith( ".hpp" )

        /* filter by cpu os or other key words */
        for ( item <- cpuList
	      if accept ) accept = name.indexOf( item ) == -1
        for ( item <- osList
	      if accept ) accept = name.indexOf( item ) == -1 
        for ( item <- miscList
	      if accept ) accept = name.indexOf( item ) == -1 
        if( accept )
            result.add( file.toString );
	    FileVisitResult.CONTINUE;
    }
}

trace( "tree walk" )
Files.walkFileTree( ".", visitor )

trace( "build db" )
import scala.sys.process._
import java.io.PrintWriter
// create cscope.files
val csfile = new PrintWriter( "cscope.files" )
for( s <- result ) csfile.println( s )
csfile.close
// run cscope
"cscope -bkqu".!

trace( "done" )
